from schemas.goods import GoodsPydantic, GoodsPydanticList, GoodsPydanticModel
from tortoise.expressions import Q

from models.order import ZhanGoods
from models.user import ZhanUser


class GoodsService(object):
    @staticmethod
    async def get_goods_list():
        return await GoodsPydanticList.from_queryset(ZhanGoods.all())

    @staticmethod
    async def get_goods(pk: int):
        return await GoodsPydanticList.from_queryset_single(ZhanGoods.get(pk=pk))

    @staticmethod
    async def create_goods(data: dict):
        return await ZhanGoods.create(**data)

    @staticmethod
    async def update_goods(pk: int, data: dict):
        await ZhanGoods.filter(pk=pk).update(**data)
        return await GoodsPydanticList.from_queryset_single(ZhanGoods.get(pk=pk))

    @staticmethod
    async def delete_goods(pk: int):
        await ZhanGoods.filter(pk=pk).delete()
        return {"msg": "success"}

    @staticmethod
    async def search_goods(value: str):
        return await GoodsPydanticList.from_queryset(ZhanGoods.filter(name__icontains=value))

    @staticmethod
    async def search_my_goods(value: str, user: ZhanUser):
        return await GoodsPydanticList.from_queryset(ZhanGoods.filter(Q(name__icontains=value) & Q(user_id=user)))

    @staticmethod
    async def search_goods_by_user(user: ZhanUser):
        return await GoodsPydanticList.from_queryset(ZhanGoods.filter(user_id=user))

    @staticmethod
    async def search_goods_by_user_and_name(user: ZhanUser, value: str):
        return await GoodsPydanticList.from_queryset(ZhanGoods.filter(Q(user_id=user) & Q(name__icontains=value)))

